import Qfpage from '../../components/Qfpage/Qfpage';
import { Table,Button,Drawer,Space,Form,Input,InputNumber,message,Popconfirm,Typography,Col,Row,Pagination } from 'antd';
import { useMemo,useEffect,useState,useLayoutEffect } from "react";
import { getAllType,addType,delType,editType } from "../../api/roomType"
import { getAllBuild } from '../../api/build';

const Room = ()=> {

    const [data, setData] = useState([]);
    const [limit, setLinit] = useState(30);
    const [page, setPage] = useState(1);
    const [total ,setTotal] = useState(0); // 总数

    //获取表格数据
    // const [pagination, setPagination] = useState({
    //     current: 1,
    //     pageSize: 10,
    //   });

    const getData = async ()=>{
        const postData = { limit,page };
        if(name) postData.name = name;
        if(price) postData.price = price;
        console.log(postData)

        let res = await getAllType(postData);
        const { success,data,count } = res;
        if(success) {
            setData(data)
            setTotal(count)
        };
    };

    // 条件过滤
    const [name, setName] = useState('');
    const [price,setPrice] = useState('');

    useLayoutEffect(()=>{
        getData()
    },[limit,page]);

    const columns = useMemo(()=>[
        {
          title: '房型名称',
          dataIndex: 'name',
          key: 'name',
        },
        {
            title: '床数量',
            dataIndex: 'beds',
            key: 'beds',
        },
        {
            title: '价格',
            dataIndex: 'price',
            key: 'price',
        },
        {
            title: '押金',
            dataIndex: 'yaPrice',
            key: 'yaPrice',
        },
        {
            title: '简称',
            dataIndex: 'shortName',
            key: 'shortName',
        },
    
    
        {
            title: '入住人数',
            dataIndex: 'liveLimit',
            key: 'liveLimit',
        },
        {
            title: '早餐券数量',
            dataIndex: 'couponNum',
            key: 'couponNum',
        },
        {
            title: '操作',
            key: 'action',
            render: (record) => {
                return (
                    <>
                        <Button 
                            type="primary" 
                            size="small" 
                            style={{marginRight:"15px"}} 
                            onClick={() => {return handleRevise(record), showDrawers()}}
                        >
                            修改
                        </Button>

                        <Popconfirm 
                            title="你确定要删除吗?" 
                            okText="确认删除"
                            cancelText="再想想" 
                            onConfirm={() => handleDelete(record._id)}
                        >
                            <Button type="primary" size="small">删除</Button>
                        </Popconfirm>
                    </>
                );
            }
           
        },
      ],[]) 


    //添加房型的操作  start
    const [form1] = Form.useForm();
    
    const [visible, setVisible] = useState(false);

    const showDrawer = () => {
        setVisible(true);
    };

    const onClose = () => {
        setVisible(false);
    };

    const onFinish = async (value) => {

        onClose()

        let res = await addType(value);
        const { success } = res;
        if(!success) return message.error('添加失败');
        message.success('添加成功');
        getData()//刷新表格
        form1.resetFields();//重置表单内容
    };

    const onFinishFailed = () => {
        console.log('Failed:', "errorInfo");
    };
    //添加房型的操作  end


    //删除房型的操作  start
    const handleDelete = async (id) => {
        console.log(id)
        let res = await delType({typeid: id});
        const { success } = res;
        if(!success) return message.error('删除失败');
        message.success('删除成功');
        getData()//刷新表格

        };
    //删除房型的操作   end


    //修改房型的操作   start
    const [form] = Form.useForm()

    const [visibles, setVisibles] = useState(false);

    const showDrawers = () => {
        setVisibles(true);
    };

    const onCloses = () => {
        setVisibles(false);
    };

    const [curRow,setCurRow] = useState(null)

    const handleRevise = async (record) => {
        form.setFieldsValue(record)
        setCurRow(record)
        };

    const onFinishs = async (type) => {

        onCloses()

        const values = type; // 得到所有的表单的值
        let res = await editType({
            ...values,
            typeid: curRow._id
        });
        const { success } = res;
        if(!success) return message.error('修改失败');
        message.success('修改成功');
        getData()//刷新表格
    };

    const onFinishFaileds = () => {
        console.log('Failed:', "errorInfo");
    };
    //修改房型的操作   end
        

    return (
        <Qfpage title='来把房型维护一下'>
            <Row gutter={10}>
                <Col span={6}>
                    <Button
                        type="primary" 
                        style={{margin:"15px"}} 
                        onClick={showDrawer}
                    >
                        添加新的房型
                    </Button>
                </Col>
                <Col span={4}>
                    <Input placeholder="输入你要查询的房型" style={{margin:"15px"}} onChange={(e)=>setName(e.target.value)}/> 
                </Col>
                <Col span={4}>
                    <Input placeholder="按价格查询"style={{margin:"15px"}} onChange={(e)=>setPrice(e.target.value)}/>
                </Col>
                <Col span={8}>
                    <Button type="primary" style={{margin:"15px"}} onClick={getData}>立即查询</Button>
                </Col>
            </Row>
            
            <Table 
                dataSource={data} 
                columns={columns} 
                rowKey="_id"
                pagination={{
                    showSizeChanger:"true",
                    pageSizeOptions:[5, 10, 20],
                    defaultPageSize:8,
                    // pageSizeOptions: limit,
                    // total,
                    // onChange(page, pageSize){
                    //    setPage(current);
                    //    setLimit(pageSize)
                 
                    // }
                  }}
            />

            <Drawer 
                title="添加类型"
                placement="right" 
                onClose={onClose} 
                visible={visible} 
                size="large"
            >
    
                <Form
                    initialValues={
                        {
                            shortName: "豪大",
                            liveLimit: 1,
                            beds: 1,
                            yaPrice: 100,
                            couponNum: 1,
                        }
                    }
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    form={form1}
                >
                    <Form.Item label="房型名称" name="name" rules={[{ required: true, message: '别急!!来把房型填了先!!!' }]}>
                        <Input placeholder="请填写房型名称" />
                    </Form.Item>
                    <Form.Item label="房间简称" name="shortName">
                        <Input placeholder="请填写房间简称" />
                    </Form.Item>
                    <Form.Item label="入住人数" name="liveLimit">
                        <InputNumber 
                            min={1} 
                            max={10} 
                        />
                    </Form.Item>
                    <Form.Item label="床数" name="beds">
                        <InputNumber 
                            min={1} 
                            max={10} 
                        />
                    </Form.Item>
                    <Form.Item label="价格" name="price" rules={[{ required: true, message: '别急!!来把价格填了先!!!' }]}>
                        <Input addonAfter={"一天"}  placeholder="请填写价格"/>
                    </Form.Item>
                    <Form.Item label="押金" name="yaPrice">
                        <Input placeholder="请填写押金" />
                    </Form.Item>
                    <Form.Item label="早餐券数量" name="couponNum">
                        <InputNumber 
                            min={1} 
                            max={10} 
                        />
                    </Form.Item>

                        <Button onClick={onClose}>取消</Button>
                        <Button type="primary" htmlType="submit">
                            立即添加
                        </Button>

                </Form>
            </Drawer>

            <Drawer 
                title="修改类型"
                placement="right" 
                onClose={onCloses} 
                visible={visibles} 
                size="large"
            >
    
                <Form
                    initialValues={
                        {
                            shortName: "豪大",
                            liveLimit: 1,
                            beds: 1,
                            yaPrice: 100,
                            couponNum: 1,
                        }
                    }
                    onFinish={onFinishs}
                    onFinishFailed={onFinishFaileds}
                    form={form}
                >
                    <Form.Item label="房型名称" name="name" rules={[{ required: true, message: '别急!!来把房型填了先!!!' }]}>
                        <Input placeholder="请填写房型名称" />
                    </Form.Item>
                    <Form.Item label="房间简称" name="shortName">
                        <Input placeholder="请填写房间简称" />
                    </Form.Item>
                    <Form.Item label="入住人数" name="liveLimit">
                        <InputNumber 
                            min={1} 
                            max={10} 
                        />
                    </Form.Item>
                    <Form.Item label="床数" name="beds">
                        <InputNumber 
                            min={1} 
                            max={10} 
                        />
                    </Form.Item>
                    <Form.Item label="价格" name="price" rules={[{ required: true, message: '别急!!来把价格填了先!!!' }]}>
                        <Input addonAfter={"一天"}  placeholder="请填写价格"/>
                    </Form.Item>
                    <Form.Item label="押金" name="yaPrice">
                        <Input placeholder="请填写押金" />
                    </Form.Item>
                    <Form.Item label="早餐券数量" name="couponNum">
                        <InputNumber 
                            min={1} 
                            max={10} 
                        />
                    </Form.Item>

                        <Button onClick={onCloses}>取消</Button>
                        <Button type="primary" htmlType="submit">
                            立即修改
                        </Button>

                </Form>
            </Drawer>

            {/* <Pagination
                total={85}
                showTotal={total => `Total ${total} items`}
                defaultPageSize={20}
                defaultCurrent={1}
            /> */}
        </Qfpage>
    )
};

export default Room